//
//  DKAuthorizeHomeViewController.m
//  DanKU
//
//  Created by 吴斌 on 2023/10/19.
//

#import "DKAuthorizeHomeViewController.h"
#import "DKMainBankCardController.h"
#import "DKHomeLoanDetailController.h"
#import "DKHomeHeadAuthorizedView.h"
#import "DKAuthHomeHeadCell.h"
#import "DKAuthHomeLimitCell.h"
#import "DKAuthHomeProductCell.h"
#import "DKAuthHomeLoanCell.h"
#import "DKAuthPrivacyAgreementCell.h"
#import "DKHomeHttp.h"
#import "MJRefresh/MJRefresh.h"
#import "DKHomeMsgAlertView.h"
#import "DKHomeAuthCongratulationAlertView.h"
#import "DKTabBarViewController.h"
#import "DKUnauthorizeProductViewController.h"
#import "DKOrderRepayViewController.h"
@interface DKAuthorizeHomeViewController ()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic, strong)UITableView * dk_authorizeHomeTableView;
@property (nonatomic, strong) DKHomeMsgAlertView *homeMsgAlertView;

@property (nonatomic, strong)DKUserProductPackModel * dk_UserProductPackMdl;//产品列表
@property (nonatomic, strong)DKUserLoanStatusModel * dk_UserLoanStatusMdl;//用户放款状态
@property (nonatomic, strong)DKOrderListModel * dk_OrderListMdl;//用户借款历史

@property (nonatomic, strong)NSArray * selectProductList;//能够选择的产品列表
@property (nonatomic, strong)DKUserProductPackSigleModel *userProductPackSigleMdl;//选择的产品
@end

@implementation DKAuthorizeHomeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = DK_Hex(@"#FAFAFA");
    [self dk_creatView];
}
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self makeUserData];
    //获取拓展信息
    [[DKAuthExtHelper defaultManager] checkExtExpired];
    [self requestUserBrhavRecordProduct:DK_ActionEnter withParmDic:@{}];
}
- (void)dk_creatView{
    WeakSelf(self)
    self.dk_authorizeHomeTableView = [[UITableView alloc] init];
    self.dk_authorizeHomeTableView.backgroundColor = UIColor.clearColor;
    self.dk_authorizeHomeTableView.delegate = self;
    self.dk_authorizeHomeTableView.dataSource = self;
    self.dk_authorizeHomeTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.dk_authorizeHomeTableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    self.dk_authorizeHomeTableView.showsVerticalScrollIndicator = NO;
    self.dk_authorizeHomeTableView.estimatedRowHeight = 0;
    self.dk_authorizeHomeTableView.estimatedSectionHeaderHeight = 0;
    self.dk_authorizeHomeTableView.estimatedSectionFooterHeight = 0;
    [self.view addSubview:self.dk_authorizeHomeTableView];
    [self.dk_authorizeHomeTableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(@(DK_IsWidthScale(0)));
        make.top.equalTo(@(DK_IsWidthScale(0)));
        make.bottom.equalTo(@(-DK_TabBar_H));
    }];
    
    MJRefreshNormalHeader  *header = [MJRefreshNormalHeader  headerWithRefreshingTarget:self refreshingAction:@selector(makeUserData)];
    [header setTitle:@"Dropdown can refresh" forState:MJRefreshStateIdle];
    [header setTitle:@"Release and refresh immediately" forState:MJRefreshStatePulling];
    [header setTitle:@"Refreshing data...." forState:MJRefreshStateRefreshing];
    header.lastUpdatedTimeLabel.hidden = YES;
    self.dk_authorizeHomeTableView.mj_header = header;
    
    self.homeMsgAlertView = [[DKHomeMsgAlertView alloc] init];
    self.homeMsgAlertView.hidden = YES;
    [self.view addSubview:self.homeMsgAlertView];
    [self.homeMsgAlertView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(@(DK_IsWidthScale(15)));
        make.right.equalTo(@(-DK_IsWidthScale(15)));
        make.height.equalTo(@(DK_IsWidthScale(90)));
        make.bottom.equalTo(@(-DK_IsWidthScale(10)-DK_SafeAreaNav_H));
    }];
    self.homeMsgAlertView.MsgAlertHidBlock = ^{
        weakSelf.homeMsgAlertView.hidden = YES;
    };
    self.homeMsgAlertView.MsgAlertGoBlock = ^(NSString * _Nonnull settled) {//跳转订单列表
        UIViewController *rootViewController = ((AppDelegate*)([UIApplication sharedApplication].delegate)).window.rootViewController;
        if ([rootViewController isKindOfClass:[DKTabBarViewController class]]) {
           
            DKTabBarViewController *tab = (DKTabBarViewController *)rootViewController;
            tab.selectedIndex = 1;
        }
        if ([DKUnauthorizeProductViewController isInitialized]) {
            [[NSNotificationCenter defaultCenter] postNotificationName:@"RefreshAppTable" object:self];
        }else{
            double delayInSeconds = 0.3;
            dispatch_time_t delayTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));
            dispatch_after(delayTime, dispatch_get_main_queue(), ^{
                [[NSNotificationCenter defaultCenter] postNotificationName:@"RefreshAppTable" object:self];
            });
        }
    };
}
- (void)makehomeMsgAlert{
    DKOrderStatusModel *orderStatusMdl = [DKGlobalHelper defaultManager].orderStatusMdl;
    if([orderStatusMdl.settled isEqualToString:@"1"]||[orderStatusMdl.underReview isEqualToString:@"1"]){
        if(![NSString isCurrentDayTime]){//不是当天显示
            self.homeMsgAlertView.hidden = NO;
            [self.homeMsgAlertView updataOrderMsg];
        }
    }else{
        self.homeMsgAlertView.hidden = YES;
    }
}
- (void)makeUserData{
    WeakSelf(self)
    dispatch_group_t group = dispatch_group_create();

    //获取用户信息
    dispatch_group_enter(group);
    [DKHomeHttp apiGetUserBaseInfoForAPI:@{} complete:^{
        dispatch_group_leave(group);
        [weakSelf.dk_authorizeHomeTableView reloadData];
    }];
    //获取用户额度
    dispatch_group_enter(group);
    [DKHomeHttp apiGetUserCreditInfoForAPI:@{} complete:^{
        dispatch_group_leave(group);
        [weakSelf.dk_authorizeHomeTableView reloadData];
    }];
    //产品列表
    dispatch_group_enter(group);
    [DKPublicHttp apiGetProductPackForAPI:@{} complete:^(DKUserProductPackModel * _Nonnull userProductPackMdl) {
        weakSelf.dk_UserProductPackMdl = userProductPackMdl;
        [weakSelf.dk_authorizeHomeTableView reloadData];
        dispatch_group_leave(group);
    }];
    //用户放款状态
    dispatch_group_enter(group);
    [DKPublicHttp apiGetUserLoanStatusForAPI:@{} complete:^(DKUserLoanStatusModel * _Nonnull userLoanStatusMdl) {
        weakSelf.dk_UserLoanStatusMdl = userLoanStatusMdl;
        [weakSelf.dk_authorizeHomeTableView reloadData];
        dispatch_group_leave(group);
    }];
    //用户借款历史
    dispatch_group_enter(group);
    NSDictionary *orderDic = @{@"pageNum":@"1",@"pageSize":@"10",@"type":@"3"};
    [DKPublicHttp apiGetOrderListForAPI:orderDic complete:^(DKOrderListModel * _Nonnull orderlist) {
        weakSelf.dk_OrderListMdl = orderlist;
        dispatch_group_leave(group);
        [weakSelf.dk_authorizeHomeTableView reloadData];
    }];
    //订单状态
    [DKPublicHttp apiOrderStateForAPI:@{} complete:^{
        [weakSelf makehomeMsgAlert];
    }];
    dispatch_group_notify(group, dispatch_get_main_queue(), ^{
        [weakSelf.dk_authorizeHomeTableView reloadData];
        //更新产品列表
        DKUserComplaintModel *dk_UserComplaintMdl = [DKGlobalHelper defaultManager].userComplaintMdl;
        [weakSelf updataSelectProductList:dk_UserComplaintMdl.unused];
        [weakSelf.dk_authorizeHomeTableView.mj_header endRefreshing];
        //提额弹框
        [weakSelf makeCongratylat];
    });
}
- (void)makeCongratylat{
    DKUserBaseInfoModel * userBaseInfoMdl = [DKGlobalHelper defaultManager].userBaseInfoMdl;
    DKUserComplaintModel * userComplaintMdl = [DKGlobalHelper defaultManager].userComplaintMdl;
    if([userBaseInfoMdl.extraAmountIsNotReminded isEqualToString:@"1"]){//提醒
        [DKHomeAuthCongratulationAlertView dk_ShowAuthCongratulationAlertViewComplete:^{
            DK_SETObject_USERDEF(NSUserDefault_UserTotle, userComplaintMdl.total);
        }];
    }else{
        DK_SETObject_USERDEF(NSUserDefault_UserTotle, userComplaintMdl.total);
    }
}
- (void)updataUserLimit:(NSString *)amount{
    [self updataSelectProductList:amount];
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:1 inSection:0];
    [self.dk_authorizeHomeTableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
}
- (void)updataSelectProductList:(NSString *)amount{
    self.selectProductList = [[NSArray alloc] init];
    int maxAmount = 0;
    int flag = -1;
    for (DKUserProductPackSigleModel *userProductPackSigleMdl in self.dk_UserProductPackMdl.packageList) {
        if([userProductPackSigleMdl.amount intValue] <= [amount intValue]){
            if([userProductPackSigleMdl.amount intValue] > maxAmount){
                self.userProductPackSigleMdl = userProductPackSigleMdl;
                maxAmount = [userProductPackSigleMdl.amount intValue];
                self.selectProductList = userProductPackSigleMdl.ProductPackageList;
                flag = 1;
            }
        }
    }
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:2 inSection:0];
    [self.dk_authorizeHomeTableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
    
    [self updataLoanAllData:flag];
}
- (void)updataLoanAllData:(int)flag{
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:3 inSection:0];
    DKAuthHomeLoanCell *dk_AuthHomeLoanCell = [self.dk_authorizeHomeTableView cellForRowAtIndexPath:indexPath];
    if(flag == -1){
        dk_AuthHomeLoanCell.amount = @"0";
    }else{
        dk_AuthHomeLoanCell.amount = self.userProductPackSigleMdl.amount;
    }
}
#pragma mark -- UITableViewDelegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 5;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if(indexPath.row == 0){
        if(!self.dk_UserLoanStatusMdl.loanFail){//放款成功
            return DK_IsWidthScale(307)+DK_SafeAreaTop;
        }else{//放款失败
            return DK_IsWidthScale(369)+DK_SafeAreaTop;
        }
    }else if (indexPath.row == 1){
        return DK_IsWidthScale(126);
    }else if (indexPath.row == 2){
        if(self.selectProductList.count){//有产品列表
            return DK_IsWidthScale(268);
        }else{//无产品列表
            return DK_IsWidthScale(169);
        }
    }else if (indexPath.row == 3){
        if(self.dk_OrderListMdl.orderRecordList.count){//用户借款历史
            return DK_IsWidthScale(115)+DK_IsWidthScale(85)*self.dk_OrderListMdl.orderRecordList.count;
        }else{
            return DK_IsWidthScale(0);
        }
    }else{
        return DK_IsWidthScale(52);
    }
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    WeakSelf(self)
    if(indexPath.row == 0){
        DKAuthHomeHeadCell * dk_AuthHomeHeadCell = [DKAuthHomeHeadCell authHomeHeadCell:tableView];
        dk_AuthHomeHeadCell.dk_UserLoanStatusMdl = self.dk_UserLoanStatusMdl;
        [dk_AuthHomeHeadCell updataHomeHeadData];
        dk_AuthHomeHeadCell.HomeTranFailBlock = ^{
            DKMainBankCardController *dk_MainBankCardCtrl = [[DKMainBankCardController alloc] init];
            [weakSelf.navigationController pushViewController:dk_MainBankCardCtrl animated:YES];
        };
        return dk_AuthHomeHeadCell;
    }else if (indexPath.row == 1){
        DKAuthHomeLimitCell *dk_AuthHomeLimitCell = [DKAuthHomeLimitCell authHomeLimitCell:tableView];
        [dk_AuthHomeLimitCell updataHomeLimitData];
        dk_AuthHomeLimitCell.AuthHomeLimitBlock = ^(NSString * _Nonnull homeLimit) {
            [weakSelf updataSelectProductList:homeLimit];
        };
        return dk_AuthHomeLimitCell;
    }else if (indexPath.row == 2){
        DKAuthHomeProductCell *dk_AuthHomeProductCell = [DKAuthHomeProductCell authHomeProductCell:tableView];
        dk_AuthHomeProductCell.dk_UserProductPackMdl = self.dk_UserProductPackMdl;
        dk_AuthHomeProductCell.selectProductList = self.selectProductList;
        dk_AuthHomeProductCell.SelectProductBlock = ^(NSArray * _Nonnull selectProductList) {
            [self requestUserBrhavRecordProduct:DK_ActionApply_Now_Click withParmDic:@{}];
            
            DKHomeLoanDetailController *dk_HomeLoanDetailCtrl = [[DKHomeLoanDetailController alloc] init];
            dk_HomeLoanDetailCtrl.selectProductList = selectProductList;
            [weakSelf.navigationController pushViewController:dk_HomeLoanDetailCtrl animated:YES];
        };
        dk_AuthHomeProductCell.SelectSigleProductBlock = ^(DKUserProductPackageModel * _Nonnull dk_UserProductPackageMdl) {
            DKHomeLoanDetailController *dk_HomeLoanDetailCtrl = [[DKHomeLoanDetailController alloc] init];
            dk_HomeLoanDetailCtrl.dk_UserProductPackageMdl = dk_UserProductPackageMdl;
            [weakSelf.navigationController pushViewController:dk_HomeLoanDetailCtrl animated:YES];
        };
        return dk_AuthHomeProductCell;
    }else if(indexPath.row == 3){
        DKAuthHomeLoanCell *dk_AuthHomeLoanCell = [DKAuthHomeLoanCell authHomeLoanCell:tableView];
        dk_AuthHomeLoanCell.dk_OrderListMdl = self.dk_OrderListMdl;
        dk_AuthHomeLoanCell.amount = self.userProductPackSigleMdl.amount;
        dk_AuthHomeLoanCell.MsgAlertGoBlock = ^{
            [self requestUserBrhavRecordProduct:DK_ActionMy_Bills_Click withParmDic:@{}];

            UIViewController *rootViewController = ((AppDelegate*)([UIApplication sharedApplication].delegate)).window.rootViewController;
            if ([rootViewController isKindOfClass:[DKTabBarViewController class]]) {
               
                DKTabBarViewController *tab = (DKTabBarViewController *)rootViewController;
                tab.selectedIndex = 1;// 跳转待还款页面
            }
            if ([DKUnauthorizeProductViewController isInitialized]) {
                [[NSNotificationCenter defaultCenter] postNotificationName:@"RefreshTable" object:self];
            }else{
                double delayInSeconds = 0.3;
                dispatch_time_t delayTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));
                dispatch_after(delayTime, dispatch_get_main_queue(), ^{
                    [[NSNotificationCenter defaultCenter] postNotificationName:@"RefreshTable" object:self];
                });
            }
        };
        dk_AuthHomeLoanCell.MsgOrderDetailGoBlock = ^(DKOrderRecordListModel * _Nonnull orderRecordListMdl) {//订单详情页面
            DKOrderRepayViewController *repay = [DKOrderRepayViewController new];
            repay.dateSouce = orderRecordListMdl;
            [weakSelf.navigationController pushViewController:repay animated:YES];
        };
        return dk_AuthHomeLoanCell;
    }else{
        DKAuthPrivacyAgreementCell *dk_AuthPrivacyAgreementCell = [DKAuthPrivacyAgreementCell authStartAuthenticationCell:tableView];
        dk_AuthPrivacyAgreementCell.CheckPrivacyAgreementBlock = ^{
//            DKWebViewController * dk_WebViewCtrl = [[DKWebViewController alloc] init];
//            dk_WebViewCtrl.webUrl = DK_PrivacyAgreement;
            DKWebViewController * dk_WebViewCtrl = [[DKWebViewController alloc] initWithUrl:DK_PrivacyAgreement withIsNavBar:YES];
            dk_WebViewCtrl.hidesBottomBarWhenPushed = YES;
            [weakSelf.navigationController pushViewController:dk_WebViewCtrl animated:YES];
        };
        return dk_AuthPrivacyAgreementCell;
    }
}
- (void)requestUserBrhavRecordProduct:(NSString *)action withParmDic:(NSDictionary *)parmDic{
    [DKPublicHttp apiUserBrhavRecordForAPI:parmDic withPageName:DK_Products withAction:action complete:^{
            
    } fail:^{
            
    }];
}
@end
